package cn.wizzer.app.web.modules.controllers.user;

import cn.wizzer.app.user.modules.models.UserFocus;
import cn.wizzer.app.user.modules.services.UserFocusService;
import cn.wizzer.app.web.commons.filter.ApiTokenFilter;
import cn.wizzer.app.web.commons.ulog.annotation.ULog;
import cn.wizzer.framework.base.Result;
import cn.wizzer.framework.filter.ParamFilter;
import com.alibaba.dubbo.config.annotation.Reference;
import io.swagger.annotations.Api;
import org.nutz.dao.Cnd;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.mvc.Mvcs;
import org.nutz.mvc.annotation.*;

@Api(value = "/api/user/focus", tags = "用户关注")
@IocBean
@At("/api/user/focus")
public class ApiUserFocusController {
    @Inject
    @Reference
    private UserFocusService userFocusService;

    // 关注列表
    @At("/list")
    @Ok("json:{locked:'disabled|anchor|roomManager|sessionDisabled',ignoreNull:true}")
    @Filters({@By(type = ApiTokenFilter.class), @By(type = ParamFilter.class)})
    public Object list(@Param("pageNumber") int pageNumber, @Param("pageSize") int pageSize) {
        String userId = Mvcs.getReq().getHeader("appid");
        return Result.success().addData(userFocusService.listPage(pageNumber, pageSize, userId));
    }

    // 添加关注
    @At("/on")
    @Ok("json")
    @Filters({@By(type = ApiTokenFilter.class), @By(type = ParamFilter.class)})
    @ULog(tag = "用户添加关注", msg = "添加关注主播: ${userFocus.anchorId}")
    public Object focusOn(@Param("..") UserFocus userFocus){
        String appid = Mvcs.getReq().getHeader("appid");
        userFocus.setUserId(appid);
        // 防止重复插入
        UserFocus fetch = userFocusService.fetch(Cnd.where("userId", "=", appid).and("anchorId", "=", userFocus.getAnchorId()));
        if (null == fetch) {
            userFocusService.insert(userFocus);
        } else if (fetch.getDelFlag()) {
            // 取关再关注，更改delFlag。
            fetch.setDelFlag(false);
            userFocusService.update(fetch);
        }
        return Result.success();
    }


    // 取消关注
    @At("/cancel")
    @Ok("json")
    @Filters({@By(type = ApiTokenFilter.class), @By(type = ParamFilter.class)})
    @ULog(tag = "用户取消关注", msg = "取消关注主播: ${userFocus.anchorId}")
    public Object cancel(@Param("anchorId") String anchorId) {
        String appid = Mvcs.getReq().getHeader("appid");
        userFocusService.vDelete(Cnd.where("userId", "=", appid).and("anchorId", "=", anchorId));
        return Result.success();
    }
    // 检测关注
    @At("/check")
    @Ok("json")
    @Filters({@By(type = ApiTokenFilter.class), @By(type = ParamFilter.class)})
    public Object check(@Param("anchorId") String anchorId) {
        String appid = Mvcs.getReq().getHeader("appid");
        return Result.success(userFocusService.fetch(Cnd.where("userId", "=", appid)
                .and("anchorId", "=", anchorId).and("delFlag","=",false))!=null);
    }

}
